package patterns.flyWeight.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

public class ConnectionPool {
	private Vector<Connection> pool;
	
	
	//共有属性
	private String url = "jdbc:mysql://localhost:3306/test";
	private String username = "root";
	private String password = "root";
	private String DriverClassName = "com.mysql.jdbc.Driver";
	
	
	private int poolSize = 10;
	private static ConnectionPool instance;
	private Connection conn;
	
	private ConnectionPool(){
		pool = new Vector<Connection>(poolSize);
		
		for(int i=0;i<poolSize;i++){
			try {
				Class.forName(DriverClassName);
				conn = DriverManager.getConnection(url, username, password);
				pool.add(conn);
			} catch (ClassNotFoundException | SQLException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	public synchronized void release(Connection conn){
		pool.add(conn);
	}
	
	public synchronized Connection getConnection(){
		if (pool.size()>0) {
			Connection conn = pool.get(0);
			pool.remove(conn);
			return conn;
		}else {
			return null;
		}
	}
	
	public static ConnectionPool getConnectionPool(){
		if (instance==null) {
			instance = new ConnectionPool();
		}
		return instance;
	}
}
